<template>
  <div class="paper-main">
    <div class="paper-header">
      <el-form
        label-position="top"
        label-width="100px"
        :model="tempDataSource"
        style="padding-top: 0px"
      >
        <el-row>
          <el-col :span="4" :offset="1">
            <el-form-item label="试卷">
              {{ questionList.name }}
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="考生">
              {{ questionList.testItems.userId }}
            </el-form-item>
          </el-col>
          <!-- <el-col :span="4">
            <el-form-item label="考试时长">
              {{ questionList.testItems.endTime }}分
            </el-form-item>
          </el-col> -->
          <el-col :span="4">
            <el-form-item label="倒计时间">
              <span class="downTime">{{
                hour
                  ? hourString + ":" + minuteString + ":" + secondString
                  : minuteString + ":" + secondString
              }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="2" :offset="9">
            <Button @click="commitTestItem()" type="success">提交试卷</Button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div ref="paperLeft" class="paper-left">
      <div class="paper-title">
        <h1><i class="el-icon-s-grid"></i>答题卡</h1>
        <div v-for="(item, ques) in questionList.testSections" :key="ques">
          <h4>{{ item.name }}</h4>
          <el-button
            class="answer-button"
            circle
            size="small"
            v-for="(id, index) in item.quesesList"
            :key="index"
            >{{ index + 1 }}</el-button
          >
        </div>
      </div>
    </div>
    <div ref="paperContent" class="paper-content">
      <div class="subject" v-for="(item, ques) in questionList.testSections" :key="ques">
        <div>
          <div class="subject-title">
            <h2>{{ item.name }}</h2>
            <span
              >（共 {{ item.quesIdList.length }} 题，合计 {{ item.totalScore }} 分）</span
            >
          </div>
          <el-card class="box-card">
            <div v-for="(id, index) in item.quesesList" :key="index">
              <div slot="header" class="clearfix">
                <el-tag effect="dark"> {{ index + 1 }} </el-tag>
                <span>{{ id }}</span>
                <span>({{ item.totalScore / item.quesesNum }}分)</span>
              </div>
              <el-radio-group
                v-if="item.type == 'singleSelect'"
                v-model="singleSelectAnswer[index]"
                @click.native="saveTests()"
              >
                <el-radio
                  v-for="(opt, option) in item.options[index]"
                  :key="option"
                  :label="option"
                  class="answer-radio"
                  >{{ opt }}</el-radio
                >
              </el-radio-group>
              <!-- <el-checkbox-group
              v-if="item.questionType === 2"
              v-model="item.examineAnswer"
            >
              <el-checkbox
                v-for="(opts, options) in item.optionAll"
                :key="options"
                :label="opts.pqaId"
                class="answer-checkbox"
                >{{ opts.answerContent }}</el-checkbox
              >
            </el-checkbox-group> -->
              <el-radio-group
                v-if="item.type == 'judgement'"
                v-model="judgementAnswer[index]"
              >
                <el-radio
                  @click.native="saveTests()"
                  :disabled="disabledAnswer"
                  label="是"
                  class="answer-radio"
                  >对</el-radio
                >
                <el-radio
                  @click.native="saveTests()"
                  :disabled="disabledAnswer"
                  label="否"
                  class="answer-radio"
                  >错</el-radio
                >
              </el-radio-group>
              <el-input
                :disabled="disabledAnswer"
                v-if="item.type == 'fillInBlank'"
                v-model="fillInBlankAnswer[index]"
                @click="saveTests()"
                resize="none"
                maxlength="150"
              >
              </el-input>
            </div>
            <!-- <el-input :disabled="disabledAnswer"  v-if="sub.type===5" type="textarea" :rows="10"  v-model="sub.examineAnswer" resize="none" maxlength="2000" @blur="answerButtionCheck($event,item,sub)"> </el-input> -->
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { get, post, del, put } from "@/axios";
export default {
  data() {
    return {
      testList: [],
      questionList: [],
      singleSelectAnswer: [],
      singleAnswer: [],
      judgementAnswer: [],
      fillInBlankAnswer: [],
      quesAndAnswerAnswer: [],
      testJSON: {
        totalScore: 0,
        studentScore: 0,
        sectionList: [],
      },
      examDuration: 90,
      //倒计小时
      hour: "",
      //倒计分钟
      minute: "",
      //倒计秒
      second: "",
      //计时器
      promiseTimer: "",
      //数据源
      tempDataSource: {},
      //答题卡激活项
      answerCardActiveName: [],
      //组装后数据集
      convertDatas: [],
      //禁止答题
      disabledAnswer: false,
      //禁止阅卷
      disabledRead: false,
    };
  },
  created() {
    this.viewTest();
  },
  computed: {
    hourString() {
      return this.hour < 10 ? "0" + this.hour : "" + this.hour;
    },
    minuteString() {
      return this.minute < 10 ? "0" + this.minute : "" + this.minute;
    },
    secondString() {
      return this.second < 10 ? "0" + this.second : "" + this.second;
    },
  },
  beforeMount() {
    this.updateCountdown();
    // setInterval(() => {
    //   // 发起请求的方法
    //   this.saveTests();
    // }, 60000); // 60000毫秒为一分钟
  },
  mounted() {
    let remainTime = this.examDuration * 60;
    if (remainTime > 0) {
      this.hour = Math.floor((remainTime / 3600) % 24);
      this.minute = Math.floor((remainTime / 60) % 60);
      this.second = Math.floor(remainTime % 60);
      this.countDowm();
    }
  },
  methods: {
    async commitTestItem() {
      let testId = this.questionList.testItems.testId;
      // try {
      //   let res = await get("/visualResourceLibrary/questionnaire/test/" + id);
      //   console.log(res.data.data);
      //   this.testList = res.data.data;
      //   console.log(this.testList.sectionsList[0].answersList);
      //   this.testJSON.sectionList[0].answerList = this.testList.sectionsList[0].answersList;
      //   this.testJSON.sectionList[1].answerList = this.testList.sectionsList[1].answersList;
      //   this.testJSON.sectionList[2].answerList = this.testList.sectionsList[2].answersList;
      //   this.testJSON.sectionList[3].answerList = this.testList.sectionsList[3].answersList;
      // } catch (e) {
      //   this.$Message.error("修改失败");
      //   console.log(e);
      // }
      this.submitTest();
      // this.judgmentQuestion();
      let formData = new FormData();

      // console.log(this.testJSON);
      let testJSON = JSON.stringify(this.testJSON);
      // console.log(testJSON);
      formData.append("testJSON", testJSON);
      try {
        let res = await post(
          "/visualResourceLibrary/questionnaire/test/commit/" + testId,
          formData
        );
        this.$Message.success("提交成功");
        this.$router.back(-1);
        // console.log(res.data.data);
      } catch (e) {
        this.$Message.error("修改失败");
        console.log(e);
      }
    },
    async saveTests() {
      let id = 0;
      id = this.questionList.testItems.testId;
      // try {
      //   let res = await get("/visualResourceLibrary/questionnaire/test/" + id);
      //   console.log(res.data.data);
      //   this.testList = res.data.data;
      //   console.log(this.testList.sectionsList[0].answersList);
      //   this.testJSON.sectionList[0].answerList = this.testList.sectionsList[0].answersList;
      //   this.testJSON.sectionList[1].answerList = this.testList.sectionsList[1].answersList;
      //   this.testJSON.sectionList[2].answerList = this.testList.sectionsList[2].answersList;
      //   this.testJSON.sectionList[3].answerList = this.testList.sectionsList[3].answersList;
      // } catch (e) {
      //   this.$Message.error("修改失败");
      //   console.log(e);
      // }
      this.submitTest();
      // this.judgmentQuestion();
      let formData = new FormData();

      // console.log(this.testJSON);
      let testJSON = JSON.stringify(this.testJSON);
      // console.log(testJSON);
      formData.append("testJSON", testJSON);
      try {
        let res = await post(
          "/visualResourceLibrary/questionnaire/test/setTestItem/" + id,
          formData
        );
        // console.log(res.data.data);
      } catch (e) {
        this.$Message.error("修改失败");
        console.log(e);
      }
    },
    submitTest() {
      // console.log(this.singleSelectAnswer);
      this.singleAnswer = [];
      for (let i = 0; i < this.questionList.testSections[0].quesIdList.length; ) {
        this.singleAnswer.push(" ");
        i++;
      }

      for (let i = 0; i < this.questionList.testSections[0].quesIdList.length; ) {
        if (this.singleSelectAnswer[i] === 0) {
          this.singleAnswer[i] = "A";
        }
        if (this.singleSelectAnswer[i] === 1) {
          this.singleAnswer[i] = "B";
        }
        if (this.singleSelectAnswer[i] === 2) {
          this.singleAnswer[i] = "C";
        }
        if (this.singleSelectAnswer[i] === 3) {
          this.singleAnswer[i] = "D";
        } else if (this.singleSelectAnswer[i] === " ") {
          this.singleAnswer[i] = " ";
        }
        i++;
      }
      // console.log(this.singleAnswer);
      this.testJSON.totalScore = 0;
      for (let i = 0; i < this.questionList.testSections.length; ) {
        this.testJSON.totalScore =
          this.testJSON.totalScore + this.questionList.testSections[i].totalScore;
        i++;
      }
      // console.log(this.testJSON.totalScore);
      // console.log(this.questionList.testSections.length);
      // console.log(this.questionList.testSections[0].quesesNum);
      let j = 0;
      this.testJSON.sectionList = [];
      for (let i = 0; i < this.questionList.testSections.length; ) {
        if (this.questionList.testSections[i].quesIdList.length > 0) {
          // console.log(this.questionList.testSections.length);
          this.testJSON.sectionList.push({
            id: "",
            size: 0,
            quesIdList: [],
            responseList: [],
            answerList: [],
            answerResult: [],
          });
          this.testJSON.sectionList[j].id = this.questionList.testSections[i].id;
          this.testJSON.sectionList[j].size = this.questionList.testSections[i].quesesNum;
          // console.log(this.questionList.testSections[0].quesesNum);
          this.testJSON.sectionList[j].quesIdList = this.questionList.testSections[
            i
          ].quesIdList;
          // console.log(this.singleAnswer);
          if (this.questionList.testSections[i].type == "singleSelect") {
            this.testJSON.sectionList[j].responseList = this.singleAnswer;
          }
          if (this.questionList.testSections[i].type == "judgement") {
            this.testJSON.sectionList[j].responseList = this.judgementAnswer;
          }
          j++;
        }
        i++;
      }
      // console.log(this.testJSON.sectionList);
      // for (let i = 0; i < this.questionList.testSections.length; ) {
      //   if (this.questionList.testSection[i].quesesNum > 0) {
      //     this.testJSON.sectionList[i].id = this.questionList.testSections[i].id;
      //     this.testJSON.sectionList[i].size = this.questionList.testSections[i].quesesNum;
      //     this.testJSON.sectionList[i].quesIdList = this.questionList.testSections[i].quesIdList;

      //     if (this.questionList.testSection[i].type == "singleSelect") {
      //       this.testJSON.sectionList[i].responseList = this.singleAnswer;
      //     }

      //     if (this.questionList.testSection[i].type == "judgement") {
      //       this.testJSON.sectionList[i].responseList = this.judgementAnswer;
      //     }
      //   }
      //   i++;
      // }
      // this.testJSON.sectionList[0].id = this.questionList.testSections[0].id;
      // this.testJSON.sectionList[0].size = this.questionList.testSections[0].quesesNum;
      // this.testJSON.sectionList[0].quesIdList = this.questionList.testSections[0].quesIdList;
      // this.testJSON.sectionList[0].responseList = this.singleAnswer;
      // console.log(this.testJSON.sectionList[0].responseList);
      // this.testJSON.sectionList[1].id = this.questionList.testSections[1].id;
      // this.testJSON.sectionList[1].size = this.questionList.testSections[1].quesesNum;
      // this.testJSON.sectionList[1].quesIdList = this.questionList.testSections[1].quesIdList;
      // this.testJSON.sectionList[1].responseList = this.fillInBlankAnswer;
      // this.testJSON.sectionList[2].id = this.questionList.testSections[2].id;
      // this.testJSON.sectionList[2].size = this.questionList.testSections[2].quesesNum;
      // this.testJSON.sectionList[2].quesIdList = this.questionList.testSections[2].quesIdList;
      // console.log(this.judgementAnswer);
      // this.testJSON.sectionList[2].responseList = this.judgementAnswer;
      // this.testJSON.sectionList[3].id = this.questionList.testSections[3].id;
      // this.testJSON.sectionList[3].size = this.questionList.testSections[3].quesesNum;
      // this.testJSON.sectionList[3].quesIdList = this.questionList.testSections[3].quesIdList;
      // this.testJSON.sectionList[3].responseList = this.quesAndAnswerAnswer;
    },
    // async viewTestContent() {
    //   let id = 0;
    //   id = this.questionList.testItems.testId;
    //   try {
    //     let res = await get("/visualResourceLibrary/questionnaire/test/" + id);
    //     console.log(res.data.data);
    //     this.testList = res.data.data;
    //     console.log(this.testList.sectionsList[0].answersList);
    //     this.testJSON.sectionList[0].answerList = this.testList.sectionsList[0].answersList;
    //     this.testJSON.sectionList[1].answerList = this.testList.sectionsList[1].answersList;
    //     this.testJSON.sectionList[2].answerList = this.testList.sectionsList[2].answersList;
    //     this.testJSON.sectionList[3].answerList = this.testList.sectionsList[3].answersList;
    //   } catch (e) {
    //     this.$Message.error("修改失败");
    //     console.log(e);
    //   }
    // },
    updateCountdown() {
      let endtime = "";
      endtime = this.questionList.testItems.endTime;
      // console.log(endtime);
      var targetTime = new Date(endtime).getTime();

      // 当前时间
      var currentTime = new Date().getTime();

      // 计算时间差
      var timeDiff = targetTime - currentTime;

      // 将时间差转换为分钟
      var minutesDiff = Math.floor(timeDiff / (1000 * 60));

      // console.log("倒计时（分钟）：" + minutesDiff);
      // if(minutesDiff+1===0){

      // }
      this.examDuration = minutesDiff + 1;
    },
    viewTest() {
      this.questionList = this.$route.query.value;
      // console.log(this.questionList);
      if (this.questionList.testItems.answerJson !== null) {
        let answerList = JSON.parse(this.questionList.testItems.answerJson);
        // console.log(answerList);

        this.singleAnswer = answerList.sectionList[0].responseList;
        // console.log(this.singleAnswer);

        for (let i = 0; i < this.questionList.testSections[0].quesIdList.length; ) {
          if (this.singleAnswer[i] === "A") {
            this.singleSelectAnswer[i] = 0;
          }
          if (this.singleAnswer[i] === "B") {
            this.singleSelectAnswer[i] = 1;
          }
          if (this.singleAnswer[i] === "C") {
            this.singleSelectAnswer[i] = 2;
          }
          if (this.singleAnswer[i] === "D") {
            this.singleSelectAnswer[i] = 3;
          }
          // if (this.singleSelectAnswer[i] === 1) {
          //   this.singleAnswer[i] = "B";
          // }
          // if (this.singleSelectAnswer[i] === 2) {
          //   this.singleAnswer[i] = "C";
          // }
          // if (this.singleSelectAnswer[i] === 3) {
          //   this.singleAnswer[i] = "D";
          // } else if (this.singleSelectAnswer[i] === " ") {
          //   this.singleAnswer[i] = " ";
          // }
          i++;
        }
        // console.log(this.singleSelectAnswer);
      }
    },

    // judgmentQuestion() {
    //   let singleSelectScore = 0;
    //   let fillInBlankScore = 0;
    //   let judgementScore = 0;
    //   if (this.testJSON.sectionList[0].answerList.length > 0) {
    //     this.testJSON.sectionList[0].answerResult = [];
    //     for (let i = 0; i < this.testJSON.sectionList[0].answerList.length; i++) {
    //       if (
    //         this.testJSON.sectionList[0].answerList[i] ===
    //         this.testJSON.sectionList[0].responseList[i]
    //       ) {
    //         this.testJSON.sectionList[0].answerResult.push(true);
    //       } else {
    //         this.testJSON.sectionList[0].answerResult.push(false);
    //       }
    //     }
    //     let count = 0;
    //     for (let i = 0; i < this.testJSON.sectionList[0].answerList.length; i++) {
    //       if (this.testJSON.sectionList[0].answerResult[i] === true) {
    //         count++;
    //       }
    //     }
    //     singleSelectScore =
    //       (count / this.testJSON.sectionList[0].answerList.length) *
    //       this.questionList.testSections[0].totalScore;
    //   }

    //   if (this.testJSON.sectionList[1].answerList.length > 0) {
    //     this.testJSON.sectionList[1].answerResult = [];
    //     for (let i = 0; i < this.testJSON.sectionList[1].answerList.length; i++) {
    //       if (
    //         this.testJSON.sectionList[1].answerList[i] ===
    //         this.testJSON.sectionList[1].responseList[i]
    //       ) {
    //         this.testJSON.sectionList[1].answerResult.push(true);
    //       } else {
    //         this.testJSON.sectionList[1].answerResult.push(false);
    //       }
    //     }
    //     let count = 0;
    //     for (let i = 0; i < this.testJSON.sectionList[1].answerList.length; i++) {
    //       if (this.testJSON.sectionList[1].answerResult[i] === true) {
    //         count++;
    //       }
    //     }
    //     fillInBlankScore =
    //       (count / this.testJSON.sectionList[1].answerList.length) *
    //       this.questionList.testSections[1].totalScore;
    //   }

    //   if (this.testJSON.sectionList[2].answerList.length > 0) {
    //     this.testJSON.sectionList[2].answerResult = [];
    //     for (let i = 0; i < this.testJSON.sectionList[2].answerList.length; i++) {
    //       if (
    //         this.testJSON.sectionList[2].answerList[i] ===
    //         this.testJSON.sectionList[2].responseList[i]
    //       ) {
    //         this.testJSON.sectionList[2].answerResult.push(true);
    //       } else {
    //         this.testJSON.sectionList[2].answerResult.push(false);
    //       }
    //     }
    //     let count = 0;
    //     for (let i = 0; i < this.testJSON.sectionList[2].answerList.length; i++) {
    //       if (this.testJSON.sectionList[2].answerResult[i] === true) {
    //         count++;
    //       }
    //     }
    //     judgementScore =
    //       (count / this.testJSON.sectionList[2].answerList.length) *
    //       this.questionList.testSections[2].totalScore;
    //   }
    //   this.testJSON.studentScore = singleSelectScore + fillInBlankScore + judgementScore;
    //   console.log(this.testJSON.studentScore);
    // },
    countDowm() {
      let self = this;
      clearInterval(this.promiseTimer);
      this.promiseTimer = setInterval(function () {
        if (self.hour === 0 && self.minute === 0 && self.second === 0) {
          self.disabledAnswer = true;
        }
        if (self.hour === 0) {
          if (self.minute !== 0 && self.second === 0) {
            self.second = 59;
            self.minute -= 1;
          } else if (self.minute === 0 && self.second === 0) {
            self.second = 0;
            self.$emit("countDowmEnd", true);
            clearInterval(self.promiseTimer);
          } else {
            self.second -= 1;
          }
        } else {
          if (self.minute !== 0 && self.second === 0) {
            self.second = 59;
            self.minute -= 1;
          } else if (self.minute === 0 && self.second === 0) {
            self.hour -= 1;
            self.minute = 59;
            self.second = 59;
          } else {
            self.second -= 1;
          }
        }
      }, 1000);
    },
  },
};
</script>

<style scoped>
.paper-main {
  margin: 10px;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  overflow: hidden;
}

.paper-header {
  width: 100%;
  height: 80px;
  background-color: #f7f7f7;
  position: absolute;
  top: 0;
  z-index: 1000;
  box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.1);
  -webkit-box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.1);
}

.paper-left {
  position: absolute;
  padding: 10px;
  left: 0;
  top: 80px;
  bottom: 0;
  width: 300px;
  overflow-x: hidden;
  overflow-y: auto;
  border: 1px solid #e4e4e4;
  border-top: none;
}

.paper-content {
  position: absolute;
  left: 305px;
  top: 80px;
  right: 0px;
  bottom: 45px;
  overflow-x: hidden;
  overflow-y: auto;
  box-sizing: border-box;
  padding: 10px;
  border: 1px solid #e4e4e4;
  border-top: none;
}

.paper-footer {
  position: absolute;
  padding: 5px 10px;
  left: 305px;
  right: 0;
  bottom: 0px;
  height: 45px;
  overflow: hidden;
  box-sizing: border-box;
  background-color: #f7f7f7;
  box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.1);
  -webkit-box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.1);
  text-align: center;
}

.paper-title {
  padding-left: 10px;
  width: 100%;
  height: 45px;
  line-height: 45px;
  background: #f7f7f7;
}

.paper-title h1 {
  font-size: 1.2em;
  margin: 0;
}

.downTime {
  color: rgb(230, 93, 110);
  font-size: 16px;
  font-weight: bold;
}
.answer-button {
  padding: 0px;
  color: #0a0a0a;
  background-color: #ffffff;
  border-color: #e4e4e4;
  margin-left: 10px;
  width: 30px;
  height: 30px;
}
.answer-button:hover {
  background: #ecf1ef;
  border-color: #e4e4e4;
  color: #0a0a0a;
}
.answer-button-check {
  background: #13ce66;
  border-color: #30b08f;
}

.answer-radio {
  display: list-item;
  margin: 5px 0px;
}

.answer-checkbox {
  display: list-item;
  margin: 5px 0px;
}

.subject-title {
  padding-left: 10px;
  width: 100%;
  height: 45px;
  line-height: 45px;
  background: #f7f7f7;
  box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.1);
  -webkit-box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.1);
}
.subject-title h2 {
  font-size: 16px;
  display: inline-block;
}
.subject-title span {
  font-size: 16px;
  display: inline-block;
}

.subject-remark {
  background: #f7f7f7;
}
.subject-remark .item {
  display: block;
  padding: 5px;
}
.subject-remark .title {
  font-weight: bold;
}
.el-radio >>> .el-radio__input.is-checked .el-radio__inner {
  background-color: #13ce66;
  border-color: #13ce66;
}

.el-radio-button >>> .el-radio-button__inner {
  padding: 10px;
}

.el-collapse-item h2 {
  width: 150px;
  font-size: 14px;
  display: inline-block;
}
.el-form--label-top >>> .el-form-item__label {
  float: none;
  display: inline-block;
  text-align: left;
  padding: 0px;
}

.el-card {
  margin: 10px;
}

.el-card >>> .el-card__header {
  background-color: #ffffff;
  padding: 0px 10px;
  line-height: 35px;
  font-size: 16px;
}
.el-card >>> .el-card__body {
  padding: 5px 20px;
}
</style>
